/*
 *
 * Copyright (c) 2001-2019 泛微软件.
 * 泛微协同商务系统,版权所有.
 *
 */
package com.engine.workplan.cmd.calendar;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.ParamUtil;
import com.engine.core.interceptor.CommandContext;
import com.engine.workplan.bean.WorkPlanViewBean;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日程一览表导出Excel类
 * 按照前端样式导出
 */
public class ExportExcel4HtmlCmd extends AbstractCommonCommand<Map<String, Object>> {

    /**
     * 构造方法
     * @param user
     */
    public ExportExcel4HtmlCmd(User user, Map<String, Object> params) {
        this.user = user;
        this.params = params;
    }


    /**
     *  获取日志对象
     * @return
     */
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    /**
     * 按照前端样式导出
     * @param commandContext
     * @return
     */
    @Override
    public Map<String, Object> execute(CommandContext commandContext) {

        Map ret = new HashMap();

        //获取一览表页面数据
        Map<String, Object> viewDataMap=new GetCalendarViewDataCmd(user,params).execute(commandContext);

        Map dayMap=(Map)viewDataMap.get("days");
        List dayValueList=(List)dayMap.get("value");//时间范围值

        //处理导出文件名
        String fileName = Util.null2String(params.get("filename"));
        if("".equals(fileName)){
            String beginDate ="";
            String endDate = "";
            int colCount=dayValueList.size()+1;
            if(dayValueList!=null){
                beginDate=Util.null2String(dayValueList.get(0));
                endDate=Util.null2String(dayValueList.get(dayValueList.size()-1));
            }
            if("".equals(beginDate)){
                fileName= SystemEnv.getHtmlLabelName(33959, user.getLanguage());
            }else{
                fileName= SystemEnv.getHtmlLabelName(33959, user.getLanguage())+beginDate+SystemEnv.getHtmlLabelName(83903, user.getLanguage())+endDate;
            }
        }

        try {
            HttpServletRequest request = (HttpServletRequest) params.get("request");
            String ua = request.getHeader("User-Agent").toLowerCase();
            //这里为了兼容mac系统，文件中文名乱码问题。
            if (ua.indexOf("macintosh") > -1 && ua.indexOf("chrome") < 0) {
                fileName =new String(fileName.getBytes(), "iso8859-1");
            }else{
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        fileName = StringUtils.replace(fileName, "/", "");
        fileName = StringUtils.replace(fileName, "%2F", "");
        fileName = StringUtils.replace(fileName, "+", "%20");
        fileName = Util.formatMultiLang(fileName, user.getLanguage()+"") + ".xls";


        ret.put("filename",fileName);


        List dayTitleList=(List)dayMap.get("title");//时间范围显示值
        Map confMap=(Map) viewDataMap.get("conf");
        String dataRule=Util.null2String(confMap.get("dataRule"));//1 :创建人 2：接收人
        boolean ap=(boolean)confMap.get("ap");//true：拆分上下午


        //开始画Excel
        HSSFWorkbook wb=new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();

        //一般样式
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setWrapText(true);// 自动换行

        int columnWidth=6000;//列宽

        //标题
        HSSFRow row ;
        row = sheet.createRow(0);
        row.setHeight((short) 400);//标题行高

        //标题样式
        HSSFCellStyle cellStyleHead = wb.createCellStyle();
        HSSFFont font = wb.createFont();
        HSSFPalette palette = wb.getCustomPalette();
        palette.setColorAtIndex((short) 13, (byte) (128), (byte) (128), (byte) (128));
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setBold(true);
        cellStyleHead.setFont(font);
        cellStyleHead.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyleHead.setFillForegroundColor((short) 13);
        cellStyleHead.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
        cellStyleHead.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyleHead.setBorderBottom(BorderStyle.THIN);
        cellStyleHead.setBorderLeft(BorderStyle.THIN);
        cellStyleHead.setBorderTop(BorderStyle.THIN);
        cellStyleHead.setBorderRight(BorderStyle.THIN);
        cellStyleHead.setWrapText(true);

        HSSFCell cell = null;
        cell = row.createCell(0);
        sheet.setColumnWidth(0, columnWidth);
        if("1".equals(dataRule)){//创建人
            cell.setCellValue(SystemEnv.getHtmlLabelName(882, user.getLanguage()));
        }else{//接收人
            cell.setCellValue(SystemEnv.getHtmlLabelName(15525, user.getLanguage()));
        }
        cell.setCellStyle(cellStyleHead);
        if(ap){//拆分上下午
            cell = row.createCell(1);
            cell.setCellValue("");
            cell.setCellStyle(cellStyleHead);
            sheet.setColumnWidth(1, columnWidth);
        }

        for(int i=0;i<dayTitleList.size();i++){//时间
            if(ap){//拆分上下午
                cell = row.createCell(i+2);
                sheet.setColumnWidth(i+2, columnWidth);
            }else{
                cell = row.createCell(i+1);
                sheet.setColumnWidth(i+1, columnWidth);
            }
            cell.setCellValue(Util.null2String(dayTitleList.get(i)));
            cell.setCellStyle(cellStyleHead);
        }

        if(ap){
            sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
        }

        //画数据
        List dataList=(List)viewDataMap.get("datas");//日程数据

        //先对数据处理下，方便获取
        Map<String,Object> dataMap=new HashMap<>();
        changeDateList2Map(dataList,dataMap);

        List memberList=(List)viewDataMap.get("memberids");//要显示的人员数据
        if(null!=memberList&&memberList.size()>0){
            Map<String,Object> memberMap;
            String memberId;
            Map memberDataTemp;
            Map infoMapTemp;
            List infoListTemp;
            int rowCount=1;

            //数据样式
            HSSFCellStyle dataCellStyle = wb.createCellStyle();
            dataCellStyle.setAlignment(HorizontalAlignment.LEFT); // 左对齐
            dataCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            dataCellStyle.setBorderBottom(BorderStyle.THIN);
            dataCellStyle.setBorderLeft(BorderStyle.THIN);
            dataCellStyle.setBorderTop(BorderStyle.THIN);
            dataCellStyle.setBorderRight(BorderStyle.THIN);
            dataCellStyle.setWrapText(true);// 自动换行

            for(int i=0;i<memberList.size();i++){
                row=sheet.createRow(rowCount);
                memberMap=(Map)memberList.get(i);
                if(null==memberMap) {
                    continue;
                }
                String name = Util.null2String(memberMap.get("name"));
                int ll = (name.length()%12+1)*5;
                //row.setHeightInPoints(ll);
                memberId=Util.null2String(memberMap.get("id"));

                cell = row.createCell(0);
                cell.setCellValue(Util.null2String(memberMap.get("name")));
                cell.setCellStyle(style);

                if(ap){//拆分上下午
                    cell = row.createCell(1);
                    cell.setCellValue(SystemEnv.getHtmlLabelName(16689, user.getLanguage()));//上午
                    cell.setCellStyle(style);

                    infoMapTemp=null;
                    memberDataTemp=(Map)dataMap.get(memberId);
                    if(null!=memberDataTemp){
                        infoMapTemp=(Map) memberDataTemp.get("info");
                    }
                    //画上午
                    for(int j=0;j<dayValueList.size();j++){
                        infoListTemp=null;
                        if(null!=infoMapTemp){
                            infoListTemp=(List) infoMapTemp.get(Util.null2String(dayValueList.get(j)));
                        }
                        cell = row.createCell(j+2);
                        cell.setCellStyle(dataCellStyle);
                        String value = getCellDataStr(infoListTemp);
                        String formatMultiLang = Util.formatMultiLang(value);
                        cell.setCellValue(new HSSFRichTextString(formatMultiLang));//上午
                    }
                    //画下午
                    rowCount++;
                    row=sheet.createRow(rowCount);
                    cell = row.createCell(0);
                    cell.setCellValue("");
                    cell.setCellStyle(style);

                    cell = row.createCell(1);
                    cell.setCellValue(SystemEnv.getHtmlLabelName(16690, user.getLanguage()));//下午
                    cell.setCellStyle(style);
                    infoMapTemp=null;
                    if(null!=memberDataTemp){
                        infoMapTemp=(Map) memberDataTemp.get("info_pm");
                    }
                    for(int j=0;j<dayValueList.size();j++){
                        infoListTemp=null;
                        if(null!=infoMapTemp){
                            infoListTemp=(List) infoMapTemp.get(Util.null2String(dayValueList.get(j)));
                        }
                        cell = row.createCell(j+2);
                        cell.setCellStyle(dataCellStyle);
                        String value = getCellDataStr(infoListTemp);
                        String formatMultiLang = Util.formatMultiLang(value);
                        cell.setCellValue(new HSSFRichTextString(formatMultiLang));//上午
                    }

                    sheet.addMergedRegion(new CellRangeAddress(rowCount-1,rowCount,0,0));

                }else{//不拆分上下午
                    infoMapTemp=null;
                    memberDataTemp=(Map)dataMap.get(memberId);
                    if(null!=memberDataTemp){
                        infoMapTemp=(Map) memberDataTemp.get("info");
                    }

                    //画单元格
                    for(int j=0;j<dayValueList.size();j++){
                        infoListTemp=null;
                        if(null!=infoMapTemp){
                            infoListTemp=(List) infoMapTemp.get(Util.null2String(dayValueList.get(j)));
                        }
                        cell = row.createCell(j+1);
                        cell.setCellStyle(dataCellStyle);
                        String value = getCellDataStr(infoListTemp);
                        String formatMultiLang = Util.formatMultiLang(value);
                        cell.setCellValue(new HSSFRichTextString(formatMultiLang));

                    }
                }

                rowCount++;

            }
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream input=null;
        try {
            wb.write(os);
            input = new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            input=null;
        }

        ret.put("InputStream",input);
        return ret;
    }

    /**
     * 按照人员id和开始日期时间来封装数据，方便取出
     * @param dataList
     * @param newDataMap
     */
    private void changeDateList2Map(List dataList,Map newDataMap){
        if(null==dataList||dataList.size()<=0){
            return;
        }
        Map memberMap;
        List infoList;
        List info_pmList;

        Map dataMap;
        Map infoMap;

        for(int i=0;i<dataList.size();i++){
            memberMap=(Map)dataList.get(i);
            if(null==memberMap) continue;

            dataMap=new HashMap();

            //处理上午数据
            infoMap=new HashMap();
            infoList=(List)memberMap.get("info");
            dataList2Map(infoList,infoMap);
            dataMap.put("info",infoMap);

            //处理下午数据
            infoMap=new HashMap();
            infoList=(List)memberMap.get("info_pm");
            dataList2Map(infoList,infoMap);
            dataMap.put("info_pm",infoMap);

            newDataMap.put(Util.null2String(memberMap.get("memberid")),dataMap);
        }

    }

    /**
     * 将每条日程数据封装成以开始日期为key的map
     * @param infoList 待处理list
     * @param infoMap 封装的map
     */
    private void dataList2Map(List infoList,Map infoMap){
        WorkPlanViewBean dataBean;
        List infoListTemp;
        String date;
        if(null!=infoList&&infoList.size()>0){
            for(int j=0;j<infoList.size();j++){
                dataBean=(WorkPlanViewBean)infoList.get(j);
                if(null!=dataBean){
                    date=Util.null2String(dataBean.getBegindate()) ;
                    infoListTemp=(List)infoMap.get(date);
                    if(null==infoListTemp){
                        infoListTemp=new ArrayList();
                        infoMap.put(date,infoListTemp);
                    }
                    infoListTemp.add(dataBean);
                }
            }
        }
    }

    /**
     * 获取日程数据显示字符串
     * @param infoList
     * @return
     */
    private String getCellDataStr(List infoList){
        StringBuilder retSb=new StringBuilder();
        if(null!=infoList&&infoList.size()>0){
            WorkPlanViewBean dataBean;
            for(int i=0; i<infoList.size();i++){
                dataBean=(WorkPlanViewBean)infoList.get(i);
                if(null!=dataBean){
                    retSb.append("".equals(retSb.toString())?Util.null2String(dataBean.getShowname()):"\n\n"+Util.null2String(dataBean.getShowname()));
                }
            }
        }
        return retSb.toString();
    }
}
